package net.xdclass.rbac_shiro.config;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;

/**
 * @program: rbac_shiro
 * @description: 自定义的Filter
 * // mappedValue  o -》roles[admin,root]
 * 只要有其中一个role满足即可
 * @author: rZ
 * @create: 2020-01-14 09:20
 **/
public class CustomRolesOrAuthorizationFilter extends AuthorizationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        Subject subject = getSubject(servletRequest, servletResponse);
        //获取当前访问路径所需要的角色集合
        String[] roleArray = (String[])o;
        //没有角色限制，有权限访问
        if (roleArray == null || roleArray.length==0){
            return  true;
        }
        Set<String> roles = CollectionUtils.asSet(roleArray);
        //当前subject是rolesArray中的任何一个，则有权限访问
        for (String role : roles) {
            if (subject.hasRole(role)){
                return  true;
            }
        }
        return false;
    }
}
